package com.liuche.book.auth.service.impl;

import com.liuche.book.auth.constant.RedisKeyConstants;
import com.liuche.book.auth.model.vo.verification.req.SendVerificationCodeReqVO;
import com.liuche.book.auth.service.VerificationCodeService;
import com.liuche.framework.common.enums.ResponseCodeEnum;
import com.liuche.framework.common.exception.BizException;
import com.liuche.framework.common.response.Response;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


@Slf4j
@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Response<?> send(SendVerificationCodeReqVO sendVerificationCodeReqVO) {
        // 构建 key
        String phoneKey = RedisKeyConstants.buildVerificationCodeKey(sendVerificationCodeReqVO.getPhone());

        // 校验手机号是否存在
        String code = stringRedisTemplate.opsForValue().get(phoneKey);
        if (StringUtils.isNotBlank(code)) {
            throw new BizException(ResponseCodeEnum.VERIFICATION_CODE_SEND_FREQUENTLY);
        }

        // 生成 6 位数字的验证码，redis 保存
        // code = CommonUtil.generatePhoneCode();
        code = "888888"; // 暂时默认六个8
        stringRedisTemplate.opsForValue().set(phoneKey, code, 5, TimeUnit.MINUTES);

        // 调用三方发送验证码 todo

        log.info("【发送验证码】手机：{}；code：{}", sendVerificationCodeReqVO.getPhone(), code);
        return Response.success();
    }
}
